package net.caidingke.shepherd.impl;

import com.alibaba.dubbo.config.annotation.Service;
import io.ebean.Ebean;
import io.ebean.PagedList;
import io.ebean.SqlRow;
import io.ebean.annotation.Transactional;
import net.caidingke.shepherd.LocationService;
import net.caidingke.shepherd.domain.common.City;
import net.caidingke.shepherd.utils.result.ResultGenerator;
import net.caidingke.shepherd.utils.result.ResultPage;

import java.util.List;
import java.util.Optional;

/**
 * @author bowen
 */
@Service(version = "1.0.0")
public class DefaultLocationServiceImpl implements LocationService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultPage cities(int page, int pageSize) {
        PagedList<City> pagedList = City.F.where().setFirstRow(page * pageSize).setMaxRows(pageSize).findPagedList();
        return ResultGenerator.ok(pagedList.getList(), pagedList.getPageIndex(), pagedList.getPageSize(), pagedList.getTotalCount());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createCity(String name) {
        City city = new City();
        city.setName(name);
        city.insert();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Optional<City> findCityById(Long id) {
        return Optional.ofNullable(City.F.byId(id));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Optional<City> modifyCity(Long id, String name) {
        return this.findCityById(id).map(c -> {
            c.setName(name);
            c.update();
            return c;
        });
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<SqlRow> selectNative() {
        String sql = "select * from User u left join City c on u.city_id = c.id";
        List<SqlRow> list = Ebean.createSqlQuery(sql).findList();
        System.out.println(list.size());
        return list;
    }
}
